#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc.
# 
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Tiles metadata."""


import datetime
from google.appengine.ext import webapp
import wsgiref.handlers


class LastUpdatedController(webapp.RequestHandler):
  """Returns the last updated timestamp for a tile set."""

  def get(self):
    """GET handler."""
    tiles = self.request.get('tiles')
    last = open('../zips/tiles/%s/datestamp.txt'%(tiles)).readline().strip()
    last = datetime.datetime.strptime(last, '%Y-%m-%d %H:%M')
    now = datetime.datetime.utcnow()
    delta = now - last
    if delta.days > 1:
      self.response.out.write('%dd ago' % (delta.days))
    elif delta.seconds > 3600:
      seconds = delta.seconds + delta.days * 24 * 3600
      h = seconds / 3600
      self.response.out.write('%02dh ago' % (h))
    else:
      self.response.out.write('%02dm ago' % (delta.seconds/60))
    expires = now + datetime.timedelta(seconds=60)
    self.response.headers['Expires'] = (
        expires.strftime('%a, %d %b %Y %H:%M:%S GMT'))
    self.response.headers['Cache-Control'] = 'public, max_age=60'


def main():
  app = webapp.WSGIApplication([('/tiles/lastupdated', LastUpdatedController)])
  wsgiref.handlers.CGIHandler().run(app)


if __name__ == '__main__':
  main()
